'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 任务
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var _ = require('lodash');
var dataApi = require('../libs/dataApi');
var taskFactory = require('../libs/taskFactory');
var dailyTaskMgr = require('../mgr/dailyTaskMgr');
var dailyConf = require('../config/dailyConf');

var _initTaskList = function () {
    var task_list = [];
    dataApi.daily.each(function (task_conf, task_id) {
        task_list.push(+task_id);
    });
    return task_list;
};

/**
 * 任务
 */
var dailyTaskSchema = new mongoose.Schema({
    // 玩家id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    current_task_list: {
        type: Array,
        default: _initTaskList
    },

    // 已经完成的任务列表
    complete_task_list: [Number],

    // 统计的列表
    static_list: {
        type: mongoose.Schema.Types.Mixed,
        default: {}
    },

    // 每日任务活跃度
    daily_active: {
        type: Number,
        default: 0
    },

    // 每日任务定时任务状态列表
    daily_active_schedule_task: {
        type: mongoose.Schema.Types.Mixed,
        default: {}
    },

    // 每日任务活跃度已领取列表
    daily_active_list: [Number],
});

dailyTaskSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 增加已领取状态
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.addScheduleTaskState = function (daily_task_id) {
    this.daily_active_schedule_task[daily_task_id] = this.daily_active_schedule_task[daily_task_id] || 0;
    this.daily_active_schedule_task[daily_task_id] = 1;
    this.markModified('daily_active_schedule_task');
};

/**
 * 获取领取状态  isActiveReceive
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.getScheduleTaskState = function (daily_task_id) {
    return this.daily_active_schedule_task[daily_task_id] || 0;
};

/**
 * 是否可领取活跃度奖励
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.isActiveReceive = function (active_id) {
    return _.indexOf(this.daily_active_list, active_id) == -1;
};

/**
 * 添加已经领取活跃度id
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.addReceiveActiveId = function (active_id) {
    if (this.isActiveReceive(active_id)) {
        this.daily_active_list.push(active_id);
    }
    return;
};

/**
 * 增加活跃度
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
dailyTaskSchema.methods.addDailyActive = function (add_active) {
    this.daily_active += +add_active;
};

/**
 * 获取每日任务活跃度已领取列表
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
dailyTaskSchema.methods.getDailyActiveList = function () {
    return this.daily_active_list;
};

/**
 * 获取每日任务活跃度
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
dailyTaskSchema.methods.getDailyActive = function () {
    return this.daily_active;
};

/**
 * 获取当前的任务
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
dailyTaskSchema.methods.isHaveTask = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.current_task_list, task_id) !== -1;
};

/**
 * 判断任务是否完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
dailyTaskSchema.methods.isTaskComplete = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.complete_task_list, task_id) !== -1;
};

/**
 * 是否任务能够完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
dailyTaskSchema.methods.isTaskCanComplete = function (task_id) {
    task_id = +task_id;
    var now_value = _getTaskProgress(this.static_list, task_id);
    if (!this.isHaveTask(task_id)) {
        return false;
    }
    return now_value >= _getTaskTotalProgress(task_id);
};

/**
 * 获取当前的任务
 */
dailyTaskSchema.methods.getCurrentTaskList = function () {
    return this.current_task_list;
};

/**
 * 获取任务的奖励
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
dailyTaskSchema.methods.rewardTask = function (task_id) {
    task_id = +task_id;
    if (!this.isTaskCanComplete(task_id)) {
        return false;
    }

    // 移除任务
    this.current_task_list.pull(task_id);

    // 添加到reward的列表中
    this.complete_task_list.push(task_id);
    return true;
};

/**
 * 添加一个新任务
 * @param {[type]} task_id [description]
 */
dailyTaskSchema.methods.addTask = function (task_id) {
    task_id = +task_id;

    // 如果已经完成不加入
    if (!!this.isTaskComplete(task_id)) {
        return false;
    }

    var task = this.isHaveTask(task_id);
    if (!!task) {
        return false;
    }
    this.current_task_list.push(task_id);
    return true;
};

/**
 * 获取统计的列表
 */
dailyTaskSchema.methods.getStaticList = function (task_static_type) {
    this.static_list[task_static_type] = this.static_list[task_static_type] || {};
    return this.static_list[task_static_type];
};

dailyTaskSchema.methods.setChange = function () {
    this.markModified('static_list');
};

/**
 * 刷新
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.refresh = function () {
    this.daily_active_schedule_task = {};
    this.current_task_list = _initTaskList();
    this.complete_task_list = [];
    this.daily_active_list = [];
    this.daily_active = 0;
    this.static_list = {};
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 移除任务
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
dailyTaskSchema.methods.removeTask = function (task_id) {
    task_id = +task_id;
    if (!this.isActiveReceive(task_id)) {
        return false;
    }

    // 移除任务
    this.current_task_list.pull(task_id);

    // 添加到reward的列表中
    this.complete_task_list.push(task_id);
    return true;
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
dailyTaskSchema.methods.push = function () {
    this.pushModify();
};

dailyTaskSchema.methods.pushModify = function () {
    dailyTaskMgr.sendDailyTaskChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send daily_task message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

/**
 * 获取任务的进度
 * @param  {[type]} static_list [description]
 * @param  {[type]} task_id     [description]
 * @return {[type]}             [description]
 */
var _getTaskProgress = function (static_list, task_id) {
    static_list = static_list || {};
    var task_conf = dataApi.daily.findById(task_id);
    if (!task_conf) {
        console.error('dailyTask is can not found:' + task_id);
        return 0;
    }

    var task_type = task_conf.type;
    if (!!static_list[task_type]) {
        return taskFactory.getInstance(task_type).getProgress(static_list[task_type], task_conf);
    }
    return 0;
};

/**
 * 获取任务的总进度
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _getTaskTotalProgress = function (task_id) {
    var task_conf = dataApi.daily.findById(task_id);
    if (!task_conf) {
        return 0;
    }
    return task_conf.value;
};

if (!dailyTaskSchema.options.toJSON) {
    dailyTaskSchema.options.toJSON = {};
}
/* jshint unused:false */
dailyTaskSchema.options.toJSON.transform = function (doc, ret) {
    // 处理任务进度
    var task_list = [];
    _.each(ret.current_task_list, function (task_id) {
        var daily_conf = dailyConf.getRewardList(task_id);
        if (!daily_conf) {
            console.error('daily_task_id error:', task_id);
            daily_conf = {
                player_level_max: 999999,
                player_level_min: 999999,
                priority: 999999
            };
        }

        task_list.push({
            task_id: task_id,
            progress: _getTaskProgress(ret.static_list, task_id),
            total_progress: _getTaskTotalProgress(task_id),
            player_level_max: daily_conf.player_level_max,
            player_level_min: daily_conf.player_level_min,
            priority: daily_conf.priority
        });
    });

    ret.current_task_list = _.sortBy(task_list, 'priority');

    delete ret.role_id;
    delete ret.complete_task_list;
    delete ret.static_list;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('DailyTask', dailyTaskSchema);
